package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.RegisterRequest
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class RegisterUiState(
    val isLoading: Boolean = false,
    val username: String = "",
    val password: String = "",
    val confirmPassword: String = "",
    val email: String = "",
    val nickname: String = "",
    val isPrivacyPolicyChecked: Boolean = false,
    val isUserAgreementChecked: Boolean = false,
    val error: String? = null,
    val isRegistered: Boolean = false
)

@HiltViewModel
class RegisterViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(RegisterUiState())
    val uiState: StateFlow<RegisterUiState> = _uiState.asStateFlow()
    
    fun register() {
        if (!validateInput()) {
            return
        }
        
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                val request = RegisterRequest(
                    username = uiState.value.username,
                    password = uiState.value.password,
                    email = uiState.value.email,
                    nickname = uiState.value.nickname
                )
                
                repository.register(request).collect { result ->
                    result.fold(
                        onSuccess = {
                            _uiState.update { 
                                it.copy(
                                    isLoading = false,
                                    isRegistered = true,
                                    error = null
                                )
                            }
                        },
                        onFailure = { exception ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = exception.message ?: "注册失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "注册失败"
                    )
                }
            }
        }
    }
    
    private fun validateInput(): Boolean {
        val state = uiState.value
        
        if (state.username.isBlank()) {
            _uiState.update { it.copy(error = "用户名不能为空") }
            return false
        }
        
        if (state.password.isBlank()) {
            _uiState.update { it.copy(error = "密码不能为空") }
            return false
        }
        
        if (state.confirmPassword.isBlank()) {
            _uiState.update { it.copy(error = "请确认密码") }
            return false
        }
        
        // Check if passwords match
        if (state.password != state.confirmPassword) {
            _uiState.update { it.copy(error = "密码不匹配") }
            return false
        }
        
        if (state.email.isBlank()) {
            _uiState.update { it.copy(error = "邮箱不能为空") }
            return false
        }
        
        // Validate email format
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(state.email).matches()) {
            _uiState.update { it.copy(error = "请输入有效的邮箱地址") }
            return false
        }
        
        if (state.nickname.isBlank()) {
            _uiState.update { it.copy(error = "昵称不能为空") }
            return false
        }
        
        if (!state.isPrivacyPolicyChecked) {
            _uiState.update { it.copy(error = "请同意隐私政策") }
            return false
        }
        
        if (!state.isUserAgreementChecked) {
            _uiState.update { it.copy(error = "请同意用户协议") }
            return false
        }
        
        return true
    }
    
    fun setUsername(username: String) {
        _uiState.update { it.copy(username = username) }
    }
    
    fun setPassword(password: String) {
        _uiState.update { it.copy(password = password) }
    }
    
    fun setConfirmPassword(confirmPassword: String) {
        _uiState.update { it.copy(confirmPassword = confirmPassword) }
    }
    
    fun setEmail(email: String) {
        _uiState.update { it.copy(email = email) }
    }
    
    fun setNickname(nickname: String) {
        _uiState.update { it.copy(nickname = nickname) }
    }
    
    fun setPrivacyPolicyChecked(checked: Boolean) {
        _uiState.update { it.copy(isPrivacyPolicyChecked = checked) }
    }
    
    fun setUserAgreementChecked(checked: Boolean) {
        _uiState.update { it.copy(isUserAgreementChecked = checked) }
    }
    
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}